//
//  LZLableExtension.swift
//  halikaPeso
//
//  Created by L-zh on 2024/12/16.
//

import UIKit

extension UILabel {
    /// 富文本:字体颜色
    func setupAttributeString(text:String?,changeText:String? ,color:UIColor? ) {
        guard let  text = text else {
            return;
        }
        guard let  changeText = changeText else {
            return;
        }
        if !text.contains(changeText) {
            return
        }
        let attributeString = NSMutableAttributedString(string: text)
        
        let range = (text as NSString).range(of: changeText)
        
        attributeString.addAttributes([NSAttributedString.Key.foregroundColor : color ?? UIColor.white], range: range)
        
        self.attributedText = attributeString
        
    }
    
    /// 获取NSRange: 根据关键字
    func nsRange(from range: Range<String.Index>, in string: String) -> NSRange {
        let utf16view = string.utf16
        let from = range.lowerBound.samePosition(in: utf16view)!
        let to = range.upperBound.samePosition(in: utf16view)!
        return NSRange(location: utf16view.distance(from: utf16view.startIndex, to: from),
                       length: utf16view.distance(from: from, to: to))
    }

    func getNSRange(for substring: String, in text: String) -> NSRange? {
        if let range = text.range(of: substring) {
            return nsRange(from: range, in: text)
        }
        return nil
    }
//    // 使用示例
//    let text = "0123"
//    if let nsRange = getNSRange(for: "01", in: text) {
//        print("Found '01' at \(nsRange)")
//    }
}
